package com.stylefeng.guns.modular.JobHandler;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.config.redis.RedisUtil;
import com.stylefeng.guns.modular.small.model.BizConsumer;
import com.stylefeng.guns.modular.small.service.IBizConsumerService;
import com.stylefeng.guns.modular.wehcat.api.WechatApi;
import com.stylefeng.guns.modular.wehcat.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class WxInfoHandler {

    //获取用户基本信息(UnionID机制)
    private static  final  String  USER_INFO="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    @Resource
    private IBizConsumerService iBizConsumerService;

    @Resource
    private WechatApi wechatApi;

    @Resource
    private RedisUtil  redisUtil;

    /**
     * <p>十分钟去获取一次用户的微信信息</p>
     */
    @Scheduled(fixedDelayString = "100000")
    public void getWechatInfo() {
        List<BizConsumer> list=iBizConsumerService.findConsumerOpenIdIsNOTNULL();
        if(list.size()==0){
            return;
        }
        Object  accessToken =redisUtil.get("accessToken");
        if(accessToken==null){
            accessToken =  wechatApi.getAccessToken();
            redisUtil.set("accessToken",accessToken,6000);
        }
        log.info("获取的accessToken为：{}",accessToken);
        String  url=USER_INFO.replace("ACCESS_TOKEN",accessToken.toString());
        for (BizConsumer  bizConsumer:list) {
            JSONObject  result= HttpClientUtils.httpGet(url.replace("OPENID",bizConsumer.getOpenId()));
            bizConsumer.setUpdateDate(new Date());
            bizConsumer.setWechatName(result.getString("nickname"));
//            bizConsumer.setWxInfo(JSONObject.toJSONString(result));
            iBizConsumerService.updateById(bizConsumer);
        }
    }
}
